//
//  LFPlaceholderTextView.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/4/1.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit

class LFPlaceholderTextView: UITextView {
    
   override var text: String? {
        didSet {
            //有文本有隐藏
            placeholderLabel.hidden = hasText()
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    var placeholderText: String? {
        didSet {
            placeholderLabel.text = placeholderText
        }
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        prepareUI()
        
        //通知 
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didChangText", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func didChangText() {
        
        placeholderLabel.hidden = hasText()
    }

      //MARK: -- 布局UI
    private func prepareUI() {
        
        addSubview(placeholderLabel)
        
        // 添加约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    }
    

      //MARK: -- 懒加载
    private lazy var placeholderLabel: UILabel = {
       let label = UILabel()
        label.textColor = UIColor.whiteColor()
        label.sizeToFit()
        
        return label
    }()
    
}
